<template>
  <div class="course-panel-box">
    <div class="content-box">
      <form-bar
        ref="formBarRef"
        @form-change-handle="formChangeHandle"
        :is-arrange="isArrange"
      ></form-bar>
      <div class="content">
        <div class="operation-bar">
          <WeekBox
            @week-change-handle="weekChangeHandle"
            :is-arrange="isArrange"
          ></WeekBox>
          <el-button type="primary" plain @click="arrangeHandle">
            {{ isArrange ? '退出布置' : '布置课程' }}
          </el-button>
        </div>
        <div
          class="courses-board"
          @dragover="
            (event: Event) => {
              event.preventDefault()
            }
          "
        >
          <div class="left-content" v-if="isArrange">
            <courses-tree-list
              ref="coursesTreeListRef"
              :search-bar-form="searchForm"
              @drag-end-handle="dragEndHandle"
              @preview-handle="previewHandle"
              @search-left-handle="searchLeftHandle"
            ></courses-tree-list>
          </div>
          <div class="right-content" :style="!isArrange ? 'width: 100%;' : ''">
            <template v-if="!ispPreview">
              <div class="padding-preview">
                <status-bar></status-bar>
                <class-schedule
                  :init-date-info="dateFaseForm"
                  :search-bar-info="searchForm"
                  :init-table-data="initTableData"
                  @dragenter-handle="dragenterHandle"
                  @del-course-handle="delCourseHandle"
                ></class-schedule>
              </div>
            </template>
            <template v-else>
              <div class="preview-box">
                <div class="fold-up">
                  <el-button class="btn" @click="foldUpHandle"
                    >收起预览</el-button
                  >
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import type { TreeNodeData } from 'element-plus/es/components/tree/src/tree.type.mjs'
import FormBar, { type Form } from './common/FormBar.vue'
import WeekBox, { type BaseForm } from './common/WeekBox.vue'
import CoursesTreeList from './common/CoursesTreeList.vue'
import type { Tree, SearchLeftForm } from './common/CoursesTreeList.vue'
import StatusBar from './common/StatusBar.vue'
import ClassSchedule from './common/ClassSchedule.vue'

const formBarRef = ref()

// 搜索条数据
const searchForm = ref<Form | null>(null)
// 左侧搜索条
const searchLeftForm = ref<SearchLeftForm | null>(null)
const coursesTreeListRef = ref()

// 当前周日期数据
const dateFaseForm = ref<BaseForm | null>(null)

// 是否预览
const ispPreview = ref<boolean>(false)

interface EmsSaveCoursePlanParam {
  scheduleDate: string // 排课日期
  periodId: string // 节次Id
  courseId: string // 课程Id
  courseName: string // 课程名称
  courseTreeId: string // 课程目录id
  courseTreeName: string // 课程目录名称
  teacherName: '' // 老师名称
  teacherId: string // 老师Id
  startTime: string // 课程开始时间+ 节次开始时间
  endTime: string // 课程结束时间+ 节次结束时间
  courseObjectType: string // 课程类型 (1:行政部,2:教学班)
  courseObjectId: string // 课程Id
  tenantId: string // 租户id
}
export interface SaveDragTableData {
  id: string
  courseScheduleName: string // 排课名称
  scheduleDate: string // 排课日期
  periodId: string // 节次Id
  subjectName: string // 学科名称
  subjectId: string // 学科Id
  gradeId: string // 年级id
  classType: string // 班级类型(1:行政部,2:教学班)
  classId: string // 班级id
  semesterId: string // 学期ID
  teacherName: string // 老师哦名称
  teacherId: string // 教师id
  tenantId: string // 租户id
  scheduleStatus: number | null
  emsCoursePlanH5VOList: EmsSaveCoursePlanParam[]
}

const initTableData = ref<Record<string, SaveDragTableData> | null>(null)
let targetCell: HTMLElement | null = null

const isArrange = ref<boolean>(false)
// 当前周
const weekChangeHandle = async (baseForm: BaseForm) => {
  dateFaseForm.value = baseForm
  console.log('当前周返回的数据:', dateFaseForm.value)

  getShowCourseDataApi()
  // initCourseList()
}

// 布置课程
const arrangeHandle = () => {
  isArrange.value = !isArrange.value
  // 只要点击 布置课程， 就操作一次关闭 预览内容
  ispPreview.value = false

  // 获取 搜索条的 最新数据
  searchForm.value = formBarRef.value.searchFormData()

  console.log('获取 搜索条的 最新数据:', searchLeftForm.value)
}

// 当前划入的框返回的数据
const dragenterHandle = (tar: HTMLElement | null) => {
  console.log(tar, 'tartartartar')
  targetCell = tar
}

// 左侧搜索
const searchLeftHandle = (data: SearchLeftForm) => {
  searchLeftForm.value = data
  console.log('searchLeftForm.value:', searchLeftForm.value)
}

// 拖拽返回的数据
const dragEndHandle = (node: TreeNodeData) => {
  // 拖拽结束后 判断是否移入 表格
  if (!targetCell) return false
  const dom = targetCell.querySelector(
    '.class-schedule-item'
  ) as HTMLElement | null

  if (dom) {
    dom.style.borderColor = 'transparent'
  }

  // 当前拖拽到的是周几
  const weekdayId = targetCell.dataset.weekday
    ? JSON.parse(targetCell.dataset.weekday).id
    : null
  // 当前拖拽的节次 ID
  const timeSlotId = targetCell.dataset.timeSlot
    ? JSON.parse(targetCell.dataset.timeSlot).id
    : null
  // 当前拖拽的节次 开始时间
  const timeSlotStartTime = targetCell.dataset.timeSlot
    ? JSON.parse(targetCell.dataset.timeSlot).startTime
    : null
  const timeSlotEndTime = targetCell.dataset.timeSlot
    ? JSON.parse(targetCell.dataset.timeSlot).endTime
    : null

  const prop = `${weekdayId}-${timeSlotId}`

  // 课程表内有数据(只有有数据才可以拖拽)
  if (!initTableData.value) return false
  // 找到拖拽到课程表上 对应的数据
  // 对 进行赋值操作 ：dragCurrentData.value[prop]

  // 当前表格里的数据
  // 当前拖拽的数据
  const dragCurrentInfo: Tree = node.data

  console.log(timeSlotStartTime, timeSlotEndTime, prop, dragCurrentInfo)

  initTableData.value[prop] = {
    id: initTableData.value[prop].id || '',
    courseScheduleName: dragCurrentInfo.catalogName, // 目录名称
    scheduleDate: initTableData.value[prop].scheduleDate, // 排课日期
    periodId: initTableData.value[prop].periodId, // 节次Id

    subjectName: searchForm.value?.disciplineName || '', // 学科名称 （去搜索 学科）
    subjectId: searchForm.value?.discipline || '', // 学科Id  （去搜索 学科）

    gradeId: searchForm.value?.gradeId || '', // 年级Id （去搜索 年级id）

    classType: searchForm.value?.classType || '', // 班级类型 （去搜索 班级类型

    classId: searchForm.value?.classId || '', // (去搜索 班级ID)
    semesterId: searchForm.value?.semester || '', // (去搜索 学期ID)
    teacherName: '',
    teacherId: '',
    tenantId: '', // 租户
    scheduleStatus: 0,
    emsCoursePlanH5VOList: [
      {
        scheduleDate: initTableData.value[prop].scheduleDate, // 排课日期
        periodId: initTableData.value[prop].periodId, // 节次Id
        courseId: searchLeftForm.value?.courseId || '', // (取左侧第二个框的 id)
        courseName: searchLeftForm.value?.courseName || '', // (取左侧第二个框的 name)
        courseTreeId: dragCurrentInfo.id + '', // (目录Id)
        courseTreeName: dragCurrentInfo.catalogName, // 目录名称
        teacherName: '',
        teacherId: '',
        startTime: `${initTableData.value[prop].scheduleDate} ${timeSlotStartTime}:00`, // 当前日期+ 节次开始时间
        endTime: `${initTableData.value[prop].scheduleDate} ${timeSlotEndTime}:59`, // 当前日期+ 节次结束时间
        courseObjectType: searchForm.value?.classType || '', // 班级类型 （去搜索 班级类型
        courseObjectId: searchForm.value?.classId || '', // (去搜索 班级ID)
        tenantId: '' // 租户
      }
    ]
  }
}

// 点击预览返回的数据
const previewHandle = (node: TreeNodeData) => {
  console.log(node, '点击预览返回的数据')
  ispPreview.value = true

  nextTick(() => {})
}
// 点击收起预览
const foldUpHandle = () => {
  ispPreview.value = false
  nextTick(() => {
    getShowCourseDataApi()
  })
}

// 删除课程
const delCourseHandle = () => {
  getShowCourseDataApi()
}
let classScheduleInfo: SaveDragTableData[] = []

//  模拟可排课数据
const schedulingData: SaveDragTableData[] = [
  {
    id: '',
    scheduleDate: dateFaseForm.value?.date || '',
    periodId: '1984142668204085249',
    subjectName: '',
    subjectId: '',
    classType: '',
    classId: '',
    semesterId: '',
    tenantId: '0',
    teacherName: '',
    teacherId: '',
    scheduleStatus: null,
    emsCoursePlanH5VOList: [],
    courseScheduleName: '',
    gradeId: ''
  },
  {
    id: '',
    courseScheduleName: '',
    scheduleDate: dateFaseForm.value?.date || '',
    periodId: '1984142915164704770',
    subjectName: '',
    subjectId: '',
    classType: '',
    classId: '',
    semesterId: '',
    teacherName: '',
    tenantId: '0',
    scheduleStatus: null,
    teacherId: '',
    emsCoursePlanH5VOList: [],
    gradeId: ''
  }
]
// 课程表-回显数据
const getShowCourseDataApi = async () => {
  schedulingData[0].scheduleDate = dateFaseForm.value?.date || ''
  schedulingData[1].scheduleDate = dateFaseForm.value?.date || ''
  classScheduleInfo = schedulingData

  classScheduleInfo = [...classScheduleInfo]

  initCourseList()
}

const initCourseList = () => {
  const resultData: Record<string, SaveDragTableData> = {} // 使用更通用的类型
  classScheduleInfo.forEach((item: SaveDragTableData) => {
    const index = dateFaseForm.value?.weekDates.findIndex(
      (week) => week === (item.scheduleDate as string).split(' ')[0]
    )
    if (index !== undefined && index !== -1) {
      resultData[`${index + 1}-${item.periodId}`] = item
    }
  })
  console.log(resultData, 'resultDataresultData')
  nextTick(() => {
    initTableData.value = resultData // 直接赋值，不需要类型转换
  })
}

// form 搜索条Eimt返回的数据
const formChangeHandle = (form: Form) => {
  console.log('form 搜索条Eimt返回的数据:', form)
  searchForm.value = form
  getShowCourseDataApi()
}
</script>

<style scoped lang="scss">
.course-panel-box {
  width: 100%;
  padding-top: 20px;
}
.content-box {
  .content {
    padding-top: 10px;
  }
}
.form-box {
  border-bottom: 1px solid #e5e6eb;
}
.week-box {
  padding-left: 10px;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 15px;
}

.courses-board {
  position: relative;
  margin-top: 30px;
  display: flex;
  justify-content: space-between;
  .left-content {
    width: 300px;
    height: 100%;
    border-right: 1px solid #e5e6eb;
    padding-right: 10px;
    padding-left: 20px;
    padding-top: 20px;
    box-sizing: border-box;
  }
  .right-content {
    width: calc(100% - 300px);
    box-sizing: border-box;
    min-height: 500px;
  }
  .class-schedule {
    border: 1px solid #e5e6eb;
  }
  .padding-preview {
    padding: 0 15px;
  }
}

.fold-up {
  display: flex;
  justify-content: flex-end;
  .btn {
    font-size: 14px;
    color: #165dff;
    background-color: transparent;
    margin-left: 0;
    transition: opacity 0.2s;
    border: 0;
    &:hover {
      opacity: 0.8;
    }
  }
}

:deep(.status-list) {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 24px;
  // padding-right: 20px;
  .item {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #4e5969;
    margin-left: 16px;
    .box {
      width: 46px;
      height: 20px;
      border-radius: 2px;
      margin-right: 5px;
    }
  }
}
// 未排课
:deep(.not-started) {
  background-color: #ffe5cc;
}
// 已排课
:deep(.started) {
  background-color: #d4f4d6;
}
// 不可排课
:deep(.prohibit) {
  background-color: #f2f3f5;
}
.preview-box {
  padding: 15px;
  box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.4);
}
</style>
